﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;

namespace Neotic.DataAccess.Sql
{
    public class SubQuery : IRowCollection
    {
        protected string _aliasName;
        protected SelectQuery _query;

        protected SubQuery()
        {

        }

        public SubQuery(SelectQuery q, string aliasName)
        {
            _query = q;
            _aliasName = aliasName;
        }

        public bool CanRead
        {
            get { return true; } 
        }

        public bool CanWrite
        {
            get { return false; }
        }

        public bool IsSameTable(IRowCollection r)
        {
            if (!(r is SubQuery))
                return false;

            return r.AliasName == this.AliasName;
        }

        /// <summary>
        /// Invalide dans le cas de sous-requete
        /// </summary>
        public string Name
        {
            get { throw new InvalidOperationException(); }
        }

        /// <summary>
        /// Invalide dans le cas de sous-requete
        /// </summary>
        public string Schema
        {
            get { throw new InvalidOperationException(); }
        }

        /// <summary>
        /// Invalide dans le cas de sous-requete
        /// </summary>
        public string FullName
        {
            get { throw new InvalidOperationException(); }
        }

        /// <summary>
        /// Retourne le nom aliasé de la sous requete
        /// </summary>
        public string AliasName
        {
            get { return _aliasName; }
        }

        /// <summary>
        /// Ne pas utiliser dans la cas de sous requete; utiliser ToSql pour gerer les paramètres
        /// </summary>
        public string FullAliasName
        {
            get { throw new InvalidOperationException(); }
        }

        /// <summary>
        /// Affecte le nom aliasé à la sous-requete
        /// </summary>
        /// <param name="aliasName"></param>
        /// <returns></returns>
        public IRowCollection As(string aliasName)
        {
            _aliasName = aliasName;
            return this;
        }

        /// <summary>
        /// Construit la requete SQL sous forme d'une sous-requete
        /// </summary>
        /// <param name="cmdParams"></param>
        /// <returns></returns>
        internal string ToSql(DbParameterCollection cmdParams)
        {
            return string.Concat(" (", ((IExecutableQuery<SelectQuery>)_query).ToSql(cmdParams), ") as ", _aliasName);
        }

    }
}
